package com.emex.app.web.service;

import com.emex.app.shared.data.Cost;
import com.emex.app.shared.data.CostExample;
import com.emex.app.shared.persistance.CostMapper;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Sergey Karavaev
 */
@Service
@Transactional
public class CostService {

    @Autowired
    private CostMapper costMapper;

    public int deleteCostByPrimaryKey(Integer id) {
        return costMapper.deleteByPrimaryKey(id);
    }

    public Cost insertCost(Cost record) {
        record.setDate(correctDate(record.getDate()));
        costMapper.insert(record);
        return record;
    }

    public List<Cost> selectCostByExample(CostExample costExample) {
        List<Cost> list = costMapper.selectByExample(costExample);
        correctDate(list);
        return list;
    }

    public Cost selectCostByPrimaryKey(Integer id) {
        Cost cost = costMapper.selectByPrimaryKey(id);
        cost.setDate(correctDate(cost.getDate()));
        return cost;
    }

    public Cost updateCostByPrimaryKey(Cost record) {
        record.setDate(correctDate(record.getDate()));
        costMapper.updateByPrimaryKey(record);
        return record;
    }

    public List<Cost> getAllCostsByDate(Date date) {
        CostExample costExample = new CostExample();
        costExample.createCriteria().andDateEqualTo(correctDate(date));
        return selectCostByExample(costExample);
    }

    public List<Cost> getAllCostsByDateEqualOrGrater(Date date) {
        CostExample costExample = new CostExample();
        costExample.createCriteria().andDateGreaterThanOrEqualTo(correctDate(date));
        return selectCostByExample(costExample);
    }

    private void correctDate(List<Cost> list) {
        if (null != list && !list.isEmpty()) {
            for (Cost record : list) {
                record.setDate(correctDate(record.getDate()));
            }
        }
    }

    private Date correctDate(Date op) {
        if (null != op) {
            final long hours12 = 4L * 60L * 60L * 1000L;
            Date date = new Date(op.getTime() + hours12);
            return date;
        }
        return null;
    }

    public List<Cost> getAllCostsByDateAndCostType(Date startDate, Date endDate, Integer costTypeId) {
        CostExample costExample = new CostExample();
        if (null != costTypeId) {
            costExample.createCriteria().andDateBetween(correctDate(startDate), correctDate(endDate)).
                    andCostTypeIdEqualTo(costTypeId);
        } else {
            costExample.createCriteria().andDateBetween(correctDate(startDate), correctDate(endDate));
        }

        return selectCostByExample(costExample);
    }
}
